<?php

namespace App\Models\CacheModel\chat;

use App\Models\Api\BaseCache;
use AstroTool\Cache\CacheManage;

class HzChatUserFreeNum extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.hz_chat_user_free_num';

    protected $cacheModel = 'chat.user_free_num';

    /**
     * 获取用户 免费使用次数 统计
     * @param $uid
     * @return array
     * @throws \Exception
     */
    public function getUserFreeNumData(int $uid): array
    {
        $cackeKey = date('Ymd') . ':' . $uid;
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $cackeKey)->setCacheTime(86410)->getDataAndSet(function () use ($uid)
        {
            try
            {
                $nowTime0 = strtotime(date('Y-m-d')); // 获取今天的零点时间戳

                $data = $this->where(['uid' => $uid])->field('sum(CASE WHEN type = 1 THEN `num` END) as free_num,sum(CASE WHEN type = 2 AND create_time >= ' . $nowTime0 . ' THEN `num` END) as vip_num')->find()->toArray();
            }
            catch (\Exception $e)
            {
                \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
                $data = [];
            }
            return $data;
        });

        if ($data)
        {
            return arrayKeyData2int($data, ['free_num', 'vip_num']);
        } else
        {
            return [];
        }
    }

    /**
     * 更新数据
     * @param int $uid
     * @param int $type 1=>免费次数 2=>vip次数
     * @param array $data
     * @param int $num
     * @return bool
     */
    public function UpdateData(int $uid, int $type, array $data, int $num)
    {
        try
        {
            $this->insert([
                'uid' => $uid,
                'type' => $type,
                'num' => $num,
                'create_time' => time(),
            ]);

            $cackeKey = date('Ymd') . ':' . $uid;
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $cackeKey)->setCache($data);
            return true;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
    }
}
